define([
    'jquery'
], function ($) {
    var stompClient = null;
    function getStudentList() {
        console.log("get user list");
        var list = [];
        $.ajax({
            url: "/user/list",
            type: 'GET',
            cache: false,
            async: false,
            success: function (response) {
                if (response && response.data) {
                    list = response.data;
                }
                console.log(response);
            },
            error: function (error) {
                console.log(error);
            }
        });
        return list;
    }

    function setConnected(connected) {
        $("#connect").prop("disabled", connected);
        $("#disconnect").prop("disabled", !connected);
        if (connected) {
            $("#conversation").show();
        }
        else {
            $("#conversation").hide();
        }
        $("#greetings").html("");
    }

    function connect() {
        var socket = new SockJS(PATH+'websocket/test');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/greet', function (message) {
                console.log("message", message);
                console.log("message.body", message.body);
                showGreeting(JSON.stringify(JSON.parse(message.body)));
            });
        });
    }

    function disconnect() {
        if (stompClient !== null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        // stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
        if(stompClient){
            stompClient.send("/app/hello", {},  $("#name").val());
        }else{
            console.log("stompClient is ", stompClient);
        }
    }

    function showGreeting(message) {
        $("#greetings").append("<tr><td>" + message + "</td></tr>");
    }

    $(function () {
        $("form").on('submit', function (e) {
            e.preventDefault();
        });
        $("#connect").click(function () {
            connect();
        });
        $("#disconnect").click(function () {
            disconnect();
        });
        $("#send").click(function () {
            sendName();
        });
    });
});